package mynet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * @Auther: cty
 * @Date: 2020/1/13 16:38
 * @Description:
 * @version: 1.0
 */
public class Be_UdpTalkSend implements Runnable{
    private String toIP;
    private int toPort;
    private DatagramSocket sender;
    private BufferedReader reader;
    Be_UdpTalkSend(int port, String toIP, int toPort){
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            sender = new DatagramSocket(port);
            reader = new BufferedReader(new InputStreamReader(System.in));

        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                String data = reader.readLine();
                byte[] datas = data.getBytes();  //获取输入数据
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length,
                        new InetSocketAddress(toIP,toPort));  //数据打包，指明发送地址
                sender.send(packet);  //发送

                if(data.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sender.close();  //释放资源
    }

    public static void main(String[] args) {
        Be_UdpTalkSend student = new Be_UdpTalkSend(6666,"localhost",8888);
        new Thread(student).start();
    }
}
